
const bcrypt = require('bcryptjs')

const {getUerInfo}  = require('../service/user.service')
const {userFormateError,userAlreadyExited,userIsundefined,userLoginError,userPasswordError} = require('../consitant/err.type')
const UserValidator = async (ctx,next) =>{

  const {user_name,password} = ctx.request.body
  console.log(user_name)
  if (!user_name || !password) {
    console.error('用户名或者密码为空',ctx.request.body)
    ctx.app.emit('error',userFormateError,ctx)
    return
  }

  await next();

}

const UserinfoValidator = async(ctx,next) =>{
  const {user_name} = ctx.request.body

  if(await getUerInfo({user_name})){
    ctx.app.emit('error',userAlreadyExited,ctx)
    return 
  }
  await next();
}


//密码加密中间件
const crpytPassword = async (ctx,next) =>{
  const {password} = ctx.request.body
  const  salt = bcrypt.genSaltSync(10);
  //哈希保存的是密文
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash
  await next();
}

const verifyLogin = async(ctx,next) =>{
try{
  const {user_name,password} = ctx.request.body
  let res = await getUerInfo({user_name})
  if(!res){
    console.error('用户名不存在',ctx.request.body)
    ctx.app.emit('error',userIsundefined,ctx)
    return 
  }
  if(!bcrypt.compareSync(password,res.password)){
    ctx.app.emit('error',userPasswordError,ctx)
    return
  }
}catch(err){

  console.error(err)
  ctx.app.emit('error',userLoginError,ctx)
  
}


  await next();
}
module.exports={
  UserValidator,
  UserinfoValidator,
  crpytPassword,
  verifyLogin
}